﻿using System;
using System.Data;
using System.Windows.Forms;
using Telerik.WinControls.UI;
using Zvezda.FSO2.DB;
using Zvezda.FSO2.DB.DataSetFSOTableAdapters;

namespace FSO
{
    public partial class FormNSIOrganization : Form, InterfaceObjDeleteableForm
    {
        //Объекты связанные с Организацией в рамках части по исходящем счетам
        private RadListDataItem[] _refObjects = {
                                                        new RadListDataItem("Исходящий счет"){Value = ObjctTypeEnum.INVOICE_OUT},
                                                        new RadListDataItem("Входящий платеж"){Value = ObjctTypeEnum.PAYMENT_IN},
                                                        new RadListDataItem("Договор"){Value = ObjctTypeEnum.CONTRACT},
                                                        new RadListDataItem("Счет фактура"){Value = ObjctTypeEnum.VAT_INVOICE},
                                                        new RadListDataItem("Календарный план"){Value = ObjctTypeEnum.CALENDAR_PLAN},
                                                        new RadListDataItem("Простокол согласования цены"){Value = ObjctTypeEnum.COST_PROTOCOL},
                                                        new RadListDataItem("Служебная записка"){Value = ObjctTypeEnum.DIRECT},
                                                        new RadListDataItem("Цеховая накладная"){Value = ObjctTypeEnum.GUILD_BILL}                                              
                                                     };



        private DataSetFSO.NSI_ORGANIZATIONRow _rowOrg;
        //private int _orgId;
        private bool _isNew;
		public bool AllowSave;

        public FormNSIOrganization()
        {                       
            InitializeComponent();

            _isNew = true; 
            _rowOrg = dataSetFSO1.NSI_ORGANIZATION.NewNSI_ORGANIZATIONRow();
            dataSetFSO1.NSI_ORGANIZATION.AddNSI_ORGANIZATIONRow(_rowOrg);

            this.Text = "Новая организация";
        }

        public FormNSIOrganization(DataSetFSO.NSI_ORGANIZATIONRow rowOrg)
        {
            InitializeComponent();
           
            _isNew = false;

            nsI_ORGANIZATIONTableAdapter1.Fill(dataSetFSO1.NSI_ORGANIZATION);
            _rowOrg = dataSetFSO1.NSI_ORGANIZATION.FindByID(rowOrg.ID);

            if (!_rowOrg.IsSHORT_NAMENull())
            {
                this.Text = string.Format("Организация - {0}", _rowOrg.SHORT_NAME);
            }
            else
            {
                this.Text = "Организация  - Х";
            }           
        }

        public void BindControls()
        {
            radTextBoxFullName.DataBindings.Clear();
            radTextBoxShortName.DataBindings.Clear();
            radTextBoxINN.DataBindings.Clear();
            radTextBoxKPP.DataBindings.Clear();
            radTextBoxOKPO.DataBindings.Clear();
            radTextBoxFullAddr.DataBindings.Clear();
            radTextBoxAddr1.DataBindings.Clear();
            radTextBoxAddr2.DataBindings.Clear();
            radTextBoxAddr3.DataBindings.Clear();
            radTextBoxAddr4.DataBindings.Clear();
            radTextBoxCountry.DataBindings.Clear();
            radTextBoxCity.DataBindings.Clear();
            radTextBoxPostIndex.DataBindings.Clear();
            radTextBoxContact.DataBindings.Clear();
            radTextBoxPhone.DataBindings.Clear();
            radTextBoxFax.DataBindings.Clear();

            radTextBoxFullName.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.FULL_NAMEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxShortName.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.SHORT_NAMEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxINN.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.INNColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxKPP.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.KPPColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxOKPO.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.OKPOColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxFullAddr.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.FULL_ADDRColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxAddr1.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.ADDR_1Column.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxAddr2.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.ADDR_2Column.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxAddr3.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.ADDR_3Column.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxAddr4.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.ADDR_4Column.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxCountry.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.COUNTRYColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxCity.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.CITYColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxPostIndex.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.POST_INDEXColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxContact.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.CONTACTColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxPhone.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.PHONEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            radTextBoxFax.DataBindings.Add("Text", _rowOrg, dataSetFSO1.NSI_ORGANIZATION.FAXColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
                        
        }
               

        #region IntefaceObjectForm Members

        public int Save()
        {
            int nRowsUpdatedCount = 0;

            if (_rowOrg.IsSHORT_NAMENull())
            {
                MessageBox.Show(this, "Не заполнено обязательное поле \"Короткое наименование\".\nИзменения не будут сохранены", "Обязательное поле", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                nRowsUpdatedCount = nsI_ORGANIZATIONTableAdapter1.Update(_rowOrg);              
            }

            return nRowsUpdatedCount;
        }

        public int Delete()
        {
            int nRowsDeletedCount = 0;

            if (_rowOrg != null && (int)nsI_ORGANIZATIONTableAdapter1.HasLinkOrganization(_rowOrg.ID) > 0)
            {
                MessageBox.Show(this, "Невозможно удалить организацию!", "Ошибка удаления", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                _rowOrg.Delete();
                nRowsDeletedCount = nsI_ORGANIZATIONTableAdapter1.Update(_rowOrg);
                this.Close();
            }
            
            return nRowsDeletedCount;
        }

        public string FormName
        {
            get 
            {
                if(!_isNew)
                {
                    return string.Format("NSI_Org-{0}", _rowOrg.ID);
                }
                else
                {
                    return "NSI_Org_" + DateTime.Now;
                }
            }
        }

        #endregion
        
        #region IntefaceObjectForm Members


        public int RefreshForm()
        {
            int result = 0;

            //Сохранем тот-же выбранный объект в панели выбора свзанных объектов
            int selectedIndex = radDropDownListRefObj.SelectedIndex;
            radDropDownListRefObj.SelectedIndex = -1;

            //Очищаем все таблицы
            foreach (DataTable dt in dataSetFSO1.Tables)
            {
                if (!(dt is DataSetFSO.NSI_ORGANIZATIONDataTable))
                {
                    dt.Clear();
                }
            }

            vieW_SEARCH_INVOICE_INTableAdapter1.FillByOrganizationId(dataSetFSO1.VIEW_SEARCH_INVOICE_IN, _rowOrg.ID);
            paymenT_OUTTableAdapter1.FillByOrgID(dataSetFSO1.PAYMENT_OUT, _rowOrg.ID);

            BindControls();

            radDropDownListRefObj.SelectedIndex = selectedIndex;
            return result;
        }

        #endregion

        #region Events

        private void FormNSIOrganization_Load(object sender, EventArgs e)
        {
            
            //Заполняем выпадающий список связанных элементов
            foreach (Telerik.WinControls.UI.RadListDataItem item in _refObjects)
            {
                radDropDownListRefObj.Items.Add(item);
            }

            userControlSearchInvoiceIn1.EnableFiltering = true;
            userControlSearchInvoiceIn1.OpenOnDoubleClick = true;
            userControlSearchInvoiceIn1.OwnerDataSet = dataSetFSO1;

            userControlSearchPayOut1.EnableFiltering = true;
            userControlSearchPayOut1.OpenOnDoubleClick = true;
            userControlSearchPayOut1.OwnerDataSet = dataSetFSO1;

            RefreshForm();
        }
        

        private void FormNSIOrganization_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (!AllowSave)
				return;
            if (_rowOrg.RowState == DataRowState.Added || _rowOrg.RowState == DataRowState.Modified)
            {
                DialogResult result = MessageBox.Show(this, "Были внесены изменения. Сохранить?", "Сохранить изменения?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    this.Save();
                }
                else if (result == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
                else
                {
                    _rowOrg.RejectChanges();
                }
            }
        }

        #endregion

        private void radDropDownListRefObj_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            //Очищаем все ресурсы - иначе много жрет
            foreach (Control cntrl in panelRefObj.Controls)
            {
                cntrl.Dispose();
            }

            panelRefObj.Controls.Clear();

            if (radDropDownListRefObj.SelectedItem != null)
            {
                //Очищаем все таблицы
                dataSetFSO1.View_SEARCH_CALENDAR_PLAN.Clear();
                dataSetFSO1.VIEW_SEARCH_COST_PROTOCOL.Clear();
                dataSetFSO1.VIEW_SEARCH_INVOICE_OUT.Clear();
                dataSetFSO1.VIEW_SEARCH_PAYMENT_IN.Clear();
                dataSetFSO1.VIEW_SEARCH_DIRECT.Clear();
                dataSetFSO1.VIEW_SEARCH_GUILD_BILL.Clear();
                dataSetFSO1.VIEWS_SEARCH_VAT_INVOICE.Clear();
                dataSetFSO1.VIEW_SEARCH_CONTRACT.Clear();

                //Заполнение таблицы договоров
                vieW_SEARCH_CONTRACTTableAdapter1.FillByOrganizationId(dataSetFSO1.VIEW_SEARCH_CONTRACT, _rowOrg.ID);

                switch ((ObjctTypeEnum)radDropDownListRefObj.SelectedItem.Value)
                {
                    case ObjctTypeEnum.CONTRACT:
                        panelRefObj.Controls.Add(new UserControlSearchContract() { Dock = DockStyle.Fill, EnableFiltering = true, OpenOnDoubleClick = true, OwnerDataSet = dataSetFSO1 } );
                        //vieW_SEARCH_CONTRACTTableAdapter1.FillByOrganizationId(dataSetFSO1.VIEW_SEARCH_CONTRACT, _rowOrg.ID);
                        break;
                    case ObjctTypeEnum.CALENDAR_PLAN:
                        panelRefObj.Controls.Add(new UserControlSearchCalendarPlan() { Dock = DockStyle.Fill, EnableFiltering = true, OpenOnDoubleClick = true, OwnerDataSet = dataSetFSO1 });
                        View_SEARCH_CALENDAR_PLANTableAdapter taCaledarPlan = new View_SEARCH_CALENDAR_PLANTableAdapter();
                        taCaledarPlan.ClearBeforeFill = false;
                        foreach (DataSetFSO.VIEW_SEARCH_CONTRACTRow rowContract in dataSetFSO1.VIEW_SEARCH_CONTRACT.Rows)
                        {
                            taCaledarPlan.FillByContractId(dataSetFSO1.View_SEARCH_CALENDAR_PLAN, rowContract.ID);
                        }
                        taCaledarPlan.ClearBeforeFill = true;
                        break;
                    case ObjctTypeEnum.COST_PROTOCOL:
                        panelRefObj.Controls.Add(new UserControlSeachCostProtocol() { Dock = DockStyle.Fill, EnableFiltering = true, OpenOnDoubleClick = true, OwnerDataSet = dataSetFSO1 });
                        VIEW_SEARCH_COST_PROTOCOLTableAdapter taCostPr = new VIEW_SEARCH_COST_PROTOCOLTableAdapter();
                        taCostPr.ClearBeforeFill = false;
                        foreach (DataSetFSO.VIEW_SEARCH_CONTRACTRow rowContract in dataSetFSO1.VIEW_SEARCH_CONTRACT.Rows)
                        {
                            taCostPr.FillByPid(dataSetFSO1.VIEW_SEARCH_COST_PROTOCOL, rowContract.PID);
                        }
                        taCostPr.ClearBeforeFill = true;
                        break;
                    case ObjctTypeEnum.INVOICE_OUT:
                        panelRefObj.Controls.Add(new UserControlSearchInvoiceOut() { Dock = DockStyle.Fill, EnableFiltering = true, OpenOnDoubleClick = true, OwnerDataSet = dataSetFSO1 });
                        VIEW_SEARCH_INVOICE_OUTTableAdapter taInvOut = new VIEW_SEARCH_INVOICE_OUTTableAdapter();
                        taInvOut.FillByOrgId(dataSetFSO1.VIEW_SEARCH_INVOICE_OUT, _rowOrg.ID);
                        /*
                        taInvOut.ClearBeforeFill = false;
                        foreach (DataSetFSO.VIEW_SEARCH_CONTRACTRow rowContract in dataSetFSO1.VIEW_SEARCH_CONTRACT.Rows)
                        {
                            taInvOut.FillByPID(dataSetFSO1.VIEW_SEARCH_INVOICE_OUT, rowContract.PID);
                        }
                        taInvOut.ClearBeforeFill = true;
                        */
                        break;
                    case ObjctTypeEnum.PAYMENT_IN:
                        panelRefObj.Controls.Add(new UserControlSearchPaymentIn() { Dock = DockStyle.Fill, EnableFiltering = true, OpenOnDoubleClick = true, OwnerDataSet = dataSetFSO1 });
                        VIEW_SEARCH_PAYMENT_INTableAdapter taPayIn = new VIEW_SEARCH_PAYMENT_INTableAdapter();
                        taPayIn.FillByOrgId(dataSetFSO1.VIEW_SEARCH_PAYMENT_IN, _rowOrg.ID);
                        /*
                        taPayIn.ClearBeforeFill = false;
                        foreach (DataSetFSO.VIEW_SEARCH_CONTRACTRow rowContract in dataSetFSO1.VIEW_SEARCH_CONTRACT.Rows)
                        {
                            taPayIn.FillByPID(dataSetFSO1.VIEW_SEARCH_PAYMENT_IN, rowContract.PID);
                        }
                        taPayIn.ClearBeforeFill = true;
                        */
                        break;
                    case ObjctTypeEnum.DIRECT:
                        panelRefObj.Controls.Add(new UserControlSearchDirect() { Dock = DockStyle.Fill, EnableFiltering = true, OpenOnDoubleClick = true, OwnerDataSet = dataSetFSO1 });
                        VIEW_SEARCH_DIRECTTableAdapter taDirect = new VIEW_SEARCH_DIRECTTableAdapter();
                        taDirect.ClearBeforeFill = false;
                        foreach (DataSetFSO.VIEW_SEARCH_CONTRACTRow rowContract in dataSetFSO1.VIEW_SEARCH_CONTRACT.Rows)
                        {
                            taDirect.FillByPID(dataSetFSO1.VIEW_SEARCH_DIRECT, rowContract.PID);
                        }
                        taDirect.ClearBeforeFill = true;
                        break;
                    case ObjctTypeEnum.GUILD_BILL:
                        panelRefObj.Controls.Add(new UserControlSearchGuildBill() { Dock = DockStyle.Fill, EnableFiltering = true, OpenOnDoubleClick = true, OwnerDataSet = dataSetFSO1 });
                        VIEW_SEARCH_GUILD_BILLTableAdapter taGuildBill = new VIEW_SEARCH_GUILD_BILLTableAdapter();
                        taGuildBill.ClearBeforeFill = false;
                        foreach (DataSetFSO.VIEW_SEARCH_CONTRACTRow rowContract in dataSetFSO1.VIEW_SEARCH_CONTRACT.Rows)
                        {
                            taGuildBill.FillByPID(dataSetFSO1.VIEW_SEARCH_GUILD_BILL, rowContract.PID);
                        }
                        taGuildBill.ClearBeforeFill = true;
                        break;
                    case ObjctTypeEnum.VAT_INVOICE:
                        panelRefObj.Controls.Add(new UserControlSearchVatInvoice() { Dock = DockStyle.Fill, EnableFiltering = true, OpenOnDoubleClick = true, OwnerDataSet = dataSetFSO1 });
                        VIEWS_SEARCH_VAT_INVOICETableAdapter taVatInv = new VIEWS_SEARCH_VAT_INVOICETableAdapter();
                        taVatInv.FillByOrgId(dataSetFSO1.VIEWS_SEARCH_VAT_INVOICE, _rowOrg.ID);
                        /*
                        taVatInv.ClearBeforeFill = false;
                        foreach (DataSetFSO.VIEW_SEARCH_CONTRACTRow rowContract in dataSetFSO1.VIEW_SEARCH_CONTRACT.Rows)
                        {
                            taVatInv.FillByPID(dataSetFSO1.VIEWS_SEARCH_VAT_INVOICE, rowContract.PID);
                        }
                        taVatInv.ClearBeforeFill = true;
                        */
                        break;
                    default:
                        break;
                }
            }
        }

    }
}
